package code.example.javassist.test;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class CreateSubClass {

    public static void main(String [] args){
        try {
            ClassPool classPool = ClassPool.getDefault();
            CtClass modelCtclass = classPool.get(Model.class.getName());
            CtClass ctClass  = classPool.makeClass("code.example.javassist.test.subModel");
            ctClass.setSuperclass(modelCtclass);
            CtMethod ctMethod = CtMethod.make("" +
                    "public String getA(){" +
                    "           long startTime = java.lang.System.currentTimeMillis();\n" +
                    "            String value = super.getA();\n" +
                    "            long useTime = java.lang.System.currentTimeMillis()-startTime;\n" +
                    "            java.lang.System.out.println(\"useTime:\"+useTime);\n" +
                    "             return value;\n  "+
                    "}" +
                    "",ctClass);
            ctClass.addMethod(ctMethod);
            Class classz = ctClass.toClass();
            Model model = (Model)classz.newInstance();
            model.setA("hello");
            System.out.println(model.getA());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
